const { api } = require('../../../utils/api.js');

Page({
  data: {
    userInfo: {},
    newNickname: '',
    newPhoneNumber: '',
    verificationCode: '',
    isVerifyMode: false,
    isSendingCode: false,
    codeButtonText: '发送验证码',
    countdown: 60,
    codeMessage: '',
    messageType: 'info',
    hasChanges: false
  },

  // 倒计时定时器
  countdownTimer: null,

  onLoad: function() {
    // 首次加载页面时获取用户信息
    this.getUserInfoFromServer();
    
    // 添加页面返回监听
    this.setBackButtonWarning();
  },

  onShow: function() {
    // 只有当用户未修改表单时才重新获取信息
    // 防止从其他页面返回时刷新丢失用户修改
    if (!this.data.hasChanges) {
      this.getUserInfoFromServer();
    }
  },

  onUnload: function() {
    // 页面卸载时清理定时器
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
    }
  },

  // 从服务器获取用户信息
  getUserInfoFromServer: function() {
    // 如果用户已经修改了表单但未保存，不要刷新用户信息
    if (this.data.hasChanges) {
      return;
    }
    
    const that = this;
    const token = wx.getStorageSync('token');
    
    if (!token) {
      wx.redirectTo({
        url: '/pages/index/index'
      });
      return;
    }
    
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    
    // 使用API模块获取用户信息
    api.getUserInfo(true).then(res => {
      wx.hideLoading();
      
      if (res.code === 200 && res.data && res.data.wechatUserDto) {
        const userData = res.data.wechatUserDto;
        console.log('获取到的用户数据:', userData);
        
        // 设置用户信息
        that.setData({
          userInfo: userData,
          newNickname: userData.nickName || '',
          newPhoneNumber: userData.phoneNumber || ''
        });
        
        // 更新本地存储的用户信息
        wx.setStorageSync('userInfo', userData);
      } else {
        console.warn('获取用户信息返回异常:', res);
        // 如果接口返回错误，从本地存储获取
        that.getUserInfoFromStorage();
      }
    }).catch(err => {
      wx.hideLoading();
      console.error('获取用户信息失败:', err);
      // 网络请求失败，从本地存储获取
      that.getUserInfoFromStorage();
    });
  },

  // 从本地存储获取用户信息（作为备用）
  getUserInfoFromStorage: function() {
    const that = this;
    wx.getStorage({
      key: 'userInfo',
      success: function(res) {
        that.setData({
          userInfo: res.data,
          newNickname: res.data.nickName || '',
          newPhoneNumber: res.data.phoneNumber || ''
        });
      },
      fail: function() {
        // 未登录时的处理
        wx.redirectTo({
          url: '/pages/index/index'
        });
      }
    });
  },

  // 选择图片代替头像选择
  chooseImage() {
    // 先保存当前表单中的数据，防止上传头像后刷新页面导致用户输入丢失
    const currentNickname = this.data.newNickname;
    const currentPhoneNumber = this.data.newPhoneNumber;
    const currentVerificationCode = this.data.verificationCode;
    const currentIsVerifyMode = this.data.isVerifyMode;
    
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        
        if (!tempFilePath) {
          wx.showToast({
            title: '获取头像失败',
            icon: 'none'
          });
          return;
        }
        
        // 先更新本地显示
        this.setData({
          'userInfo.avatarUrl': tempFilePath
        });
        
        // 直接使用云存储上传
        wx.showLoading({
          title: '上传中...',
          mask: true
        });
        
        // 使用云存储直接上传
        wx.cloud.uploadFile({
          cloudPath: `avatars/${Date.now()}-${Math.random().toString(36).slice(-6)}.png`,
          filePath: tempFilePath,
          success: res => {
            // 获取上传后的文件ID
            const fileID = res.fileID;
            console.log('上传成功，fileID:', fileID);
            
            // 更新头像URL为云存储ID，同时保留用户已输入的其他表单数据
            this.setData({
              'userInfo.avatarUrl': fileID,
              newNickname: currentNickname,
              newPhoneNumber: currentPhoneNumber,
              verificationCode: currentVerificationCode,
              isVerifyMode: currentIsVerifyMode,
              hasChanges: true
            });
            
            wx.showToast({
              title: '头像更新成功',
              icon: 'success'
            });
            
            // 将最新的头像地址保存到本地，但不要触发页面刷新
            const userInfo = wx.getStorageSync('userInfo') || {};
            userInfo.avatarUrl = fileID;
            wx.setStorageSync('userInfo', userInfo);
          },
          fail: err => {
            console.error('头像上传失败:', err);
            
            // 恢复用户之前输入的表单数据
            this.setData({
              newNickname: currentNickname,
              newPhoneNumber: currentPhoneNumber,
              verificationCode: currentVerificationCode,
              isVerifyMode: currentIsVerifyMode
            });
            
            wx.showToast({
              title: '头像上传失败',
              icon: 'none'
            });
          },
          complete: () => {
            wx.hideLoading();
          }
        });
      }
    });
  },
  
  // 处理昵称输入变化
  onNicknameInput(e) {
    const newValue = e.detail.value;
    this.setData({
      newNickname: newValue,
      hasChanges: newValue !== this.data.userInfo.nickName
    });
  },
  
  // 处理手机号输入变化
  onPhoneInput(e) {
    const newValue = e.detail.value;
    this.setData({
      newPhoneNumber: newValue,
      hasChanges: newValue !== this.data.userInfo.phoneNumber
    });
  },
  
  // 处理验证码输入变化
  onVerificationCodeInput(e) {
    this.setData({
      verificationCode: e.detail.value
    });
  },
  
  // 发送验证码
  sendVerificationCode() {
    const phoneNumber = this.data.newPhoneNumber;
    
    // 清空之前的提示消息
    this.setData({
      codeMessage: '',
      messageType: 'info'
    });
    
    if (!phoneNumber) {
      return wx.showToast({
        title: '请先输入手机号',
        icon: 'none'
      });
    }
    
    if (!/^1\d{10}$/.test(phoneNumber)) {
      return wx.showToast({
        title: '请输入有效的手机号',
        icon: 'none'
      });
    }
    
    this.setData({
      isSendingCode: true,
      codeButtonText: '发送中...'
    });
    
    api.sendVerificationCode(phoneNumber).then(res => {
      if (res.code === 200) {
        this.setData({
          isVerifyMode: true,
          codeButtonText: `${this.data.countdown}秒`,
          codeMessage: '验证码已发送，请注意查收',
          messageType: 'success'
        });
        
        wx.showToast({
          title: '验证码已发送',
          icon: 'success'
        });
        
        // 开始倒计时
        this.startCountdown();
      } else {
        this.setData({
          isSendingCode: false,
          codeButtonText: '发送验证码',
          codeMessage: res.msg || '发送失败，请重试',
          messageType: 'error'
        });
        
        wx.showToast({
          title: res.msg || '发送失败，请重试',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('验证码发送失败:', err);
      let errorMsg = '网络异常，请重试';
      if (err && err.msg) {
        errorMsg = err.msg;
      }
      
      this.setData({
        isSendingCode: false,
        codeButtonText: '发送验证码',
        codeMessage: errorMsg,
        messageType: 'error'
      });
      
      wx.showToast({
        title: errorMsg,
        icon: 'none'
      });
    });
  },
  
  // 开始倒计时
  startCountdown() {
    // 先清除可能存在的定时器
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
    }
    
    this.setData({ countdown: 60 });
    
    this.countdownTimer = setInterval(() => {
      if (this.data.countdown <= 1) {
        clearInterval(this.countdownTimer);
        this.setData({
          isSendingCode: false,
          codeButtonText: '重新发送',
          countdown: 60
        });
      } else {
        this.setData({
          countdown: this.data.countdown - 1,
          codeButtonText: `${this.data.countdown - 1}秒`
        });
      }
    }, 1000);
  },
  
  // 取消编辑
  cancelEdit() {
    if (this.data.hasChanges) {
      wx.showModal({
        title: '提示',
        content: '确定要放弃修改吗？',
        success: (res) => {
          if (res.confirm) {
            this.resetForm();
            wx.navigateBack();
          }
        }
      });
    } else {
      wx.navigateBack();
    }
  },

  // 重置表单
  resetForm() {
    this.setData({
      newNickname: this.data.userInfo.nickName,
      newPhoneNumber: this.data.userInfo.phoneNumber,
      verificationCode: '',
      isVerifyMode: false,
      hasChanges: false
    });
  },

  // 保存用户信息
  saveUserInfo() {
    if (!this.data.hasChanges && !this.data.userInfo.avatarUrl) {
      wx.navigateBack();
      return;
    }

    const { newNickname, newPhoneNumber, verificationCode } = this.data;
    const avatarUrl = this.data.userInfo.avatarUrl;

    // 验证昵称
    if (!newNickname.trim()) {
      wx.showToast({
        title: '昵称不能为空',
        icon: 'none'
      });
      return;
    }

    // 如果手机号有修改但没有验证码
    if (newPhoneNumber !== this.data.userInfo.phoneNumber && !verificationCode && this.data.isVerifyMode) {
      wx.showToast({
        title: '请先验证手机号',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '保存中...',
      mask: true
    });

    // 构建更新数据对象
    const updateData = {
      nickName: newNickname,
      avatarUrl: avatarUrl
    };

    // 只有当手机号有修改并且验证过时才添加
    if (newPhoneNumber !== this.data.userInfo.phoneNumber && verificationCode) {
      updateData.phoneNumber = newPhoneNumber;
      updateData.verificationCode = verificationCode;
    }

    // 调用API保存用户信息
    api.updateUserInfo(updateData).then(res => {
      if (res.code === 200) {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
        
        // 更新本地存储的用户信息
        const userInfo = wx.getStorageSync('userInfo') || {};
        userInfo.nickName = newNickname;
        userInfo.avatarUrl = avatarUrl;
        
        // 只有验证成功时才更新手机号
        if (updateData.phoneNumber) {
          userInfo.phoneNumber = newPhoneNumber;
        }
        
        wx.setStorageSync('userInfo', userInfo);
        
        // 重置变更标志
        this.setData({
          hasChanges: false
        });
        
        // 延迟返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        wx.showToast({
          title: res.msg || '保存失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('保存用户信息失败:', err);
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      });
    }).finally(() => {
      wx.hideLoading();
    });
  },

  // 设置返回按钮提示
  setBackButtonWarning: function() {
    // 只在安卓平台监听物理返回键
    if (wx.canIUse('onBackPress')) {
      wx.onBackPress(() => {
        if (this.data.hasChanges) {
          this.showDiscardChangesModal();
          return true; // 阻止默认返回行为
        }
        return false; // 不阻止默认返回行为
      });
    }
    
    // 监听页面卸载前事件
    this.beforeUnload = () => {
      if (this.data.hasChanges) {
        this.showDiscardChangesModal();
        return false; // 尝试阻止卸载
      }
      return true;
    };
    
    // 添加页面路由变化监听（仅小程序支持）
    if (wx.canIUse('beforeRouteLeave')) {
      wx.beforeRouteLeave(() => {
        if (this.data.hasChanges) {
          this.showDiscardChangesModal();
          return false; // 阻止页面离开
        }
        return true;
      });
    }
  },
  
  // 显示放弃修改的确认框
  showDiscardChangesModal: function() {
    wx.showModal({
      title: '提示',
      content: '您有未保存的修改，确定要放弃吗？',
      success: (res) => {
        if (res.confirm) {
          this.resetForm();
          this.setData({ hasChanges: false });
          wx.navigateBack({ delta: 1 });
        }
        // 用户点击取消，停留在当前页面
      }
    });
  },
}); 